package com.leaf.u.basehttp.download;


import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import okhttp3.OkHttpClient;

public class OkHttpImpl implements IHttp {

	private OkHttpClient client;

	public OkHttpImpl() {
		client = new OkHttpClient();
	}

	// public InputStream getInputStream(String url) throws IOException {
	// okhttp3.Request request = new
	// okhttp3.Request.Builder().url(url).get().build();
	// InputStream stream =
	// client.newCall(request).execute().body().byteStream();
	// return stream;
	// }

	@Override
	public Response get(Request r) throws IOException {

		okhttp3.Request.Builder okbuilder = new okhttp3.Request.Builder();
		Headers requestHeaders = r.headers(); 
		Set<String> requestHeadersNames = requestHeaders.names();
		Iterator<String> requestHeadersNameIterator = requestHeadersNames.iterator();
		while (requestHeadersNameIterator.hasNext()) {
			String name = requestHeadersNameIterator.next();
			String value = requestHeaders.get(name);
			okbuilder.addHeader(name, value);
		}
		okhttp3.Request request = okbuilder.url(r.url()).get().build();
		okhttp3.Response stream = client.newCall(request).execute();

		Headers.Builder builder = new Headers.Builder();
		okhttp3.Headers okheaders = stream.headers();
		Set<String> names = okheaders.names();
		Iterator<String> iterator = names.iterator();
		while (iterator.hasNext()) {
			String name = iterator.next();
			String value = okheaders.get(name);
			builder.add(name, value);
		}
		Headers headers = builder.build();
		Response re = new Response.Builder().setCode(stream.code())//
				.setContentLength(stream.body().contentLength())//
				.setHeaders(headers)// /
				.setInputStream(stream.body().byteStream())//
				.build();//
		return re;
	}

}
